######################################################################
### Fig 3: Inconsistencies Between theRicardo-Viner Model and Actual Trade Flows
######################################################################
rm(list=ls())

library(plyr)

## setting the working directory to the current folder
setwd(getwd())

data <- read.csv("./sic87_intra.csv", stringsAsFactors=F)

years <- unique(data$year)

exp <- imp <- data.frame()
for(i in 1:length(years)){
  year.i <- years[i]
  sub.i <- subset(data, subset=(data$year == year.i))
  exp.top10 <- sub.i[order(sub.i$exp.value, decreasing=T),][1:20,]
  imp.top10 <- sub.i[order(sub.i$imp.value, decreasing=T),][1:20,]
  exp <- rbind.fill(exp, exp.top10)
  imp <- rbind.fill(imp, imp.top10)
}

## Figure 3
pdf(file="./Figure3.pdf")
par(mar=c(5,6,4,2))
boxplot(exp_int_imp ~ year , data=exp, ylim=c(-1,1),
        yaxt='n', xaxt='n', cex.main=1.5)

axis(2, at=c(-1,0,1), label=c(-1,0,1),las=1)

mtext(side=2, "import\nonly", at=1, line=4, las=1, adj=.5, cex=1.2)
mtext(side=2, "high\nintra\nindustry\ntrade", at=0, line=4, outer=F, las=1, adj=.5, col="blue", cex=1.2)
mtext(side=2, "export\nonly", at=-1, line=4, outer=F, las=1, adj=.5, cex=1.2)

axis(1, at=c(1,4,7,10,13,16,19,22,25,28,31,34),
     labels=c("","","","","","","","","","","",""))
labels=c("1972", "1975", "1978", "1981", "1984", "1987",
    "1990", "1993", "1996", "1999", "2002", "2005")

for (i in 1:length(labels)){
  text(1.2+3*(i-1),-1.20, srt=45, adj=1, labels=labels[i], xpd=T, cex=1.2)
}

abline(h=0, col="red", lty=2)

dev.off()

